package com.lxxin.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class AnchorUtils {

    static final String[] TAG_NAMES = {"h1", "h2", "h3", "h4", "h5", "h6"};

    public static String addAnchor(String html) {
        Document doc = Jsoup.parse(html);
        List<Elements> elementsList = new ArrayList<>();
        for (String tag : TAG_NAMES) {
            if(doc.getElementsByTag(tag) != null) {
                elementsList.add(doc.getElementsByTag(tag));
            }
        }
        for (Elements elements : elementsList) {
            setAttribute(elements);
        }
        return doc.body().html();
    }

    public static void setAttribute(Elements elements) {
        for (Element element : elements) {
            element.attr("id", element.text());
        }
    }
}
